package cn.edu.sjtu.FaH.excellent;

import android.app.Service;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.util.Log;

public class ShakeService extends Service{

	private SensorManager sensorManager;
	private SensorEventListener sensorEventListener;
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		sensorEventListener = new SensorEventListener() {
			
			float previous_x = (float) 0;
			long last_time = System.currentTimeMillis();
			long last_shake = System.currentTimeMillis();
			final int SAMPLE_INTERVAL = 100;
			final int SHAKE_TIMEOUT = 500;
			final int SPEED_THRESHOLD = 350;
			int shakeCount = 0;
			@Override
			public void onAccuracyChanged(Sensor sensor, int accuracy) {
				
			}
		

			@Override
			public void onSensorChanged(SensorEvent event) {
				float[] values = event.values;
				float x = values[SensorManager.DATA_X];
				long now = System.currentTimeMillis(); 
				
				if (now - last_time>SAMPLE_INTERVAL) {
					long interval = now - last_time;
					float speed = Math.abs(x - previous_x) / interval * 10000;
					if (speed >SPEED_THRESHOLD) {
						if (now - last_shake>SHAKE_TIMEOUT) {
							shakeCount = 0;
						}
						if (++shakeCount>= 6) {
							shakeCount = 0;
							Log.d("shake", "Shake detected");
							sendBroadcast(new Intent("cn.edu.sjtu.FaH.sendSMS"));
						}
						Log.d("shake count", Integer.toString(shakeCount));
						last_shake = now;
					}
					last_time = now;
					previous_x = x;
				}
			}
			
		};
		sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_GAME);
	}
	
	@Override
	public void onDestroy() {
		sensorManager.unregisterListener(sensorEventListener);
		super.onDestroy();
	}
}